package com.uwlaser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uwlaser.domain.DataMain;
import com.uwlaser.service.mapper.DataMainMapper;
import com.uwlaser.utils.enums.DictValueEnum;
import lombok.AllArgsConstructor;
import com.uwlaser.base.PageInfo;
import com.uwlaser.base.QueryHelpMybatisPlus;
import com.uwlaser.base.impl.CommonServiceImpl;
import com.uwlaser.utils.ConvertUtil;
import com.uwlaser.utils.PageUtil;
import com.uwlaser.domain.DataProductPath;
import com.uwlaser.service.DataProductPathService;
import com.uwlaser.service.dto.DataProductPathDto;
import com.uwlaser.service.dto.DataProductPathQueryParam;
import com.uwlaser.service.mapper.DataProductPathMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import java.util.*;

/**
* @author zk-Qin
* @date 2022-05-11
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = DataProductPathService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DataProductPathServiceImpl extends CommonServiceImpl<DataProductPathMapper, DataProductPath> implements DataProductPathService {

    // private final RedisUtils redisUtils;
    private final DataProductPathMapper dataProductPathMapper;

    private final DataMainMapper dataMainMapper;

    @Override
    public PageInfo<DataProductPathDto> queryAll(DataProductPathQueryParam query, Pageable pageable) {
        IPage<DataProductPath> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<DataProductPath> page = dataProductPathMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, DataProductPathDto.class);
    }

    @Override
    public List<DataProductPathDto> queryAll(DataProductPathQueryParam query){
        return ConvertUtil.convertList(dataProductPathMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), DataProductPathDto.class);
    }

    @Override
    public DataProductPath getById(Integer id) {
        return dataProductPathMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public DataProductPathDto findById(Integer id) {
        return ConvertUtil.convert(getById(id), DataProductPathDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(DataProductPathDto resources) {
        DataProductPath entity = ConvertUtil.convert(resources, DataProductPath.class);
        return dataProductPathMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(DataProductPathDto resources){
        DataProductPath entity = ConvertUtil.convert(resources, DataProductPath.class);
        int ret = dataProductPathMapper.updateById(entity);
            QueryWrapper<DataProductPath> queryWrapper = new QueryWrapper();
            //查询该产品工艺路线
            List<DataProductPath> dataProductPaths = dataProductPathMapper.selectList(queryWrapper.lambda()
                    .eq(DataProductPath::getProductSn, entity.getProductSn()));
            //产品状态
            String stage="2";
            //循环判断所有的工序是否都已经完成
            for (DataProductPath dataProductPath : dataProductPaths) {
                //如果存在NG工序，直接不合格
                if(DictValueEnum.RESULT_NG.getValue().equals(dataProductPath.getResult())){
                    stage="0";
                    break;
                // 如果全部为OK，才视为合格
                } else if (DictValueEnum.RESULT_OK.getValue().equals(dataProductPath.getResult())){
                    stage="1";
                    continue;
                // 如果存在未完成工序，则将状态修改为初始化
                }else if(DictValueEnum.RESULT_UN.getValue().equals(dataProductPath.getResult())){
                    stage="2";
                    continue;
                }
            }
            //如果都是ok状态则修改主表为已完成
//            if (!isAllOk){
                //修改主表状态
                UpdateWrapper<DataMain> updateWrapper = new UpdateWrapper<>();
                dataMainMapper.update(null,
                        updateWrapper.lambda().eq(DataMain :: getProductSn,entity.getProductSn())
                                .set(DataMain :: getResult, stage));
//            }
            //如果修改某个工序为初始化状态则同步修改主表状态为未完成
//        }
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Integer> ids){
        // delCaches(ids);
        return dataProductPathMapper.deleteBatchIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Integer id){
        Set<Integer> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Integer id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Integer> ids) {
        for (Integer id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<DataProductPathDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (DataProductPathDto dataProductPath : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("产品SN", dataProductPath.getProductSn());
              map.put("产品型号", dataProductPath.getProductCode());
              map.put("产品类型", dataProductPath.getProductType());
              map.put("工序编码", dataProductPath.getOperationCode());
              map.put("工序名称", dataProductPath.getOperationName());
              map.put("执行顺序", dataProductPath.getExecutionOrder());
              map.put("上工序编号", dataProductPath.getUpStationCode());
              map.put("下工序编号", dataProductPath.getNextStationCode());
              map.put("是否校验", dataProductPath.getIsCheck());
              map.put("是否屏蔽", dataProductPath.getIsShield());
              map.put("当前工序结果", dataProductPath.getResult());
              map.put("返修标识", dataProductPath.getRepairSign());
              map.put("创建人", dataProductPath.getCreateBy());
              map.put("创建时间", dataProductPath.getCreateTime());
              map.put("更新人", dataProductPath.getUpdateBy());
              map.put("更新时间", dataProductPath.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
